<?php

namespace app\admin\controller\crm;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\CrmCustomerAppeal;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use think\App;
use think\facade\Cache;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\exception\ValidateException;
use think\exception;
use think\facade\Request;
use think\facade\View;
use Throwable;

//use think\exception\PDOException;


/**
 * @ControllerAnnotation(title="crm_customer")
 */
class Customer extends AdminController
{

    protected $day_cache_num_key = '';

    //商务标签
    protected $bus_standing = 'business';


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\CrmCustomer();

        $this->day_cache_num_key = date('Ymd');

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
         if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParamesScop();
            // $where[]=['status','=',1];
            # 判断是否全部客户
            if(intval($this->request->get('scope')) != 3){
                $where[]=['status','=',1];
            }

            //我的客户，默认只显示当天
            /*
            if ($this->request->get('scope',1,'intval') == 1) {
                $op = $this->request->get('op');
                if (count($where) <= 2) {
                    $op_arr = json_encode($op,true);
                    if (!isset($op_arr['to_kh_time'])) {
                        //进行查询
                        $where[] = ['to_kh_time','>=',strtotime(date('Y-m-d'))];
                        $where[] = ['to_kh_time','<=',time()];
                    }
                }
            }
            */
            $count = $this->model
                ->where($where)
                ->count();

            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                if ($this->admin['isphone'] == 0) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);

                }
                //替换
                $value['pr_user_bef'] = $adminList[$value['pr_user_bef']]['realname'] ?? '';
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $value['at_user'] = $adminList[$value['at_user']]['realname'] ?? '';
                $list[$key] = $value;
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $fields=Db::query('SELECT `jscol` FROM `system_field` WHERE (`show`=1 AND `table`="crm_customer" AND `jscol` is not null) OR `field`="to_kh_time" OR `field`="pr_user_bef" OR `field`="pr_user" order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=$v['jscol'].',';
        }

        $fields_str=str_replace(['":"{:',')}"'],['":{:',')}'],$fields_str);
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display(trim($fields_str,','));
        $this->app->view->engine()->layout($this->layout);
        $this->assignconfig('cols_fields',json_decode('['.$fields_str.']',true));
//        $this->assignconfig('parameter',['scope'=>$this->request->get('scope',1,'intval')]);
        return $this->fetch();
    }

    /**
     * 所有客资
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function allindex()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParamesScop();
            //移除固定条件
            unset($where[0]);
            sort($where);
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                if ($this->admin['isphone'] == 0) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3) . '****' . mb_substr($value['phone'], 7, 11);

                }
                //替换
                $value['pr_user_bef'] = $adminList[$value['pr_user_bef']]['realname'] ?? '';
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $value['at_user'] = $adminList[$value['at_user']]['realname'] ?? '';
                $list[$key] = $value;
            }

            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        $fields = Db::query('SELECT `jscol` FROM `system_field` WHERE (`show`=1 AND `table`="crm_customer" AND `jscol` is not null) OR `field`="to_kh_time" OR `field`="pr_user_bef" OR `field`="pr_user" order BY `sort` ASC,id DESC');
        $fields_str = '';
        foreach ($fields as $v) {
            $fields_str .= $v['jscol'] . ',';
        }

        $fields_str = str_replace(['":"{:', ')}"'], ['":{:', ')}'], $fields_str);
        $this->app->view->engine()->layout(false);
        $fields_str = $this->display(trim($fields_str, ','));
        $this->app->view->engine()->layout($this->layout);
        $this->assignconfig('cols_fields', json_decode('[' . $fields_str . ']', true));
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="公海")
     */
    public function seas()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = parent::buildTableParames();
            $where[]=['status','=',2];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();


            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                if ($this->admin['isphone'] == 0) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
                }
                //替换
                $value['pr_user_bef'] = $adminList[$value['pr_user_bef']]['realname'] ?? '';
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $value['at_user'] = $adminList[$value['at_user']]['realname'] ?? '';
                $list[$key] = $value;
            }


            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $fields=Db::query('SELECT `jscol` FROM `system_field` WHERE (`show`=1 AND `table`="crm_customer" AND `jscol` is not null AND `field` <> "at_user") OR `field`="to_gh_time" OR `field`="pr_user_bef" order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=$v['jscol'].',';
        }
//        {"field":"source","title":"客户来源","search":"select","width":100,"selectList":"{:build_select_list('crm_source','name','name')}"}
        $fields_str=str_replace(['":"{:',')}"'],['":{:',')}'],$fields_str);
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display(trim($fields_str,','));
        $this->app->view->engine()->layout($this->layout);
//            cols_fields="([{"type": "checkbox"},"+CONFIG.cols_fields+" {"width": 250, "title": "操作", "templet": ea.table.tool}])";
        $this->assignconfig('cols_fields',json_decode('['.$fields_str.']',true));
        $this->assignconfig('parameter',['scope'=>$this->request->get('scope',1,'intval')]);
        return $this->fetch();
    }

    /**
     * at_user
     * 我创建的
     *
     * @access public
     * @author liuqi
     * @return void
     */
    public function at_user()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = parent::buildTableParames();
            $where[]=['at_user','=',$this->admin['username']];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                if ($this->admin['isphone'] == 0) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
                }
                //替换
                $value['pr_user_bef'] = $adminList[$value['pr_user_bef']]['realname'] ?? '';
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $value['at_user'] = $adminList[$value['at_user']]['realname'] ?? '';
                $list[$key] = $value;
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $fields=Db::query('SELECT `jscol` FROM `system_field` WHERE (`show`=1 AND `table`="crm_customer" AND `jscol` is not null) OR `field`="to_gh_time" order BY `sort` ASC,id DESC');

        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=$v['jscol'].',';
        }
//        {"field":"source","title":"客户来源","search":"select","width":100,"selectList":"{:build_select_list('crm_source','name','name')}"}
        $fields_str=str_replace(['":"{:',')}"'],['":{:',')}'],$fields_str);
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display(trim($fields_str,','));
        $this->app->view->engine()->layout($this->layout);
        //$cols_fields="([{"type": "checkbox"},"+CONFIG.cols_fields+" {"width": 250, "title": "操作", "templet": ea.table.tool}])";
        $this->assignconfig('cols_fields',json_decode('['.$fields_str.']',true));
        $this->assignconfig('parameter',['scope'=>$this->request->get('scope',1,'intval')]);
        return $this->fetch();
    }

    /**
     * tmp_user
     * 流转客户
     *
     * @access public
     * @author liuqi
     * @return void
     */
    public function tmp_user()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = parent::buildTableParames();
            $where[]=['status','=',4];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                if ($this->admin['isphone'] == 0) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
                }
                //替换
                $value['pr_user_bef'] = $adminList[$value['pr_user_bef']]['realname'] ?? '';
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $value['at_user'] = $adminList[$value['at_user']]['realname'] ?? '';
                $list[$key] = $value;
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $fields=Db::query('SELECT `jscol` FROM `system_field` WHERE (`show`=1 AND `table`="crm_customer" AND `jscol` is not null) OR `field`="to_gh_time" order BY `sort` ASC,id DESC');

        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=$v['jscol'].',';
        }
//        {"field":"source","title":"客户来源","search":"select","width":100,"selectList":"{:build_select_list('crm_source','name','name')}"}
        $fields_str=str_replace(['":"{:',')}"'],['":{:',')}'],$fields_str);
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display(trim($fields_str,','));
        $this->app->view->engine()->layout($this->layout);
        //$cols_fields="([{"type": "checkbox"},"+CONFIG.cols_fields+" {"width": 250, "title": "操作", "templet": ea.table.tool}])";
        $this->assignconfig('cols_fields',json_decode('['.$fields_str.']',true));
        $this->assignconfig('parameter',['scope'=>$this->request->get('scope',1,'intval')]);
        return $this->fetch();
    }

/**
     * 申诉
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function appeal($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if (!empty($row['pr_user']) && !empty($row['pr_user_bef']) && $row['status'] == 2) {
            $this->error('此客资状态，无法进行申诉');
        }
        //仅创建人
        if ($row['at_user'] != $this->admin['username']) {
            $this->error('此客资不归属您，无法进行申诉');
        }

        //查询当前负责人
        $admin = new Admin();
        $pr_bef_admin = $admin->where(['username' => $row['pr_user_bef']])->find();
        $adminGroup = new AuthGroup();

        if ($this->request->isPost()) {
            $post = $this->request->post();
            //验证客户联系方式
            if (empty($post['explain'])) {
                $this->error('请填写申诉说明');
            }
            try {
                $time = time();
                $appealdata['explain'] = $post['explain'];
                $appealdata['customer_id'] = $id;
                $appealdata['create_time'] = $time;
                //新增申诉记录
                $appealModel = new CrmCustomerAppeal();
                $appealModel->save($appealdata);


               //无对应前负责人，则分配给商户部负责人
                $pr_user_info = ['user_name' => 'panjian','email' => '1342301895@qq.com'];
                /*
                //查询是否有前负责人
                if (!empty($pr_bef_admin)) {
                    //查询前负责人所在组
                    $pr_bef_group = $adminGroup::find($pr_bef_admin['group_id']);
                    if (!empty($pr_bef_group)) {
                        //查询前负责人所在组上级组
                        $pid_group = $adminGroup::find($pr_bef_group['pid']);
                        if (!empty($pid_group)) {
                            //查询组上组级管理人员
                            $pid_admin = $admin->where([['group_id','=',$pid_group['id']],['admin_id','<>',1]])->find();
                            if (!empty($pid_admin)) {
                                $pr_user_info = $pid_admin;
                            }
                        }
                    }
                }
                */
                $content = '客资ID:'.$row['id'].'，被标记为无效客资，现创建人员对客资进行了申诉。';
                $content .= '申请说明：【'.$post['explain']."】\n"."\r\n";
                $content .= '现此客资被分配到您账户下，请进行跟进处理';
                $send = send_email($pr_user_info['email'], '客资申诉提醒',$content);

                $data['status'] = 1;
                //重置为未选择有效状态客资
                $data['yx_status'] = -1;
                $data['wx_remark'] = '';
                $data['to_kh_time'] = $time;
                $data['pr_user_bef'] = '';
                $data['pr_user'] = $pr_user_info['user_name'];
                $save = $row->save($data);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }


        $fields_str = '<div class="layui-form-item"><label class="layui-form-label">申诉说明</label><div class="layui-input-block"><textarea name="explain" class="layui-textarea" placeholder="请输入申诉说明">{$row["explain"]|default=""}</textarea></div></div>';

        $this->app->view->engine()->layout(false);

        $fields_str = $this->display($fields_str, ['row' => $row]);
        $this->app->view->engine()->layout($this->layout);
        $this->assign('fields_str', $fields_str);
        return $this->fetch();
    }


/**
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function atedit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if (!empty($row['pr_user']) || !empty($row['pr_user_bef'])) {
            $this->error('此客资已被领取，无法修改');
        }
        //仅创建人
        if ($row['at_user'] != $this->admin['username']) {
            $this->error('此客资不归属您，无法修改');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post=$this->param_to_str($post);
            $this->verifyFields($post);

            //验证客户联系方式
            if (empty($post['phone']) && empty($post['wechat']) && empty($post['qq'])) {
                $this->error('客户联系电话、微信号、QQ必须填写一种');
            }

            if (!empty($post['phone']) && $info = $this->model->where([['phone','=',trim($post['phone'])],['id','<>',$row['id']]])->find()) {
                $this->error('系统中已经存在相同手机号');
            }

            if (!empty($post['wechat']) && $this->model->where([['wechat','=',trim($post['wechat'])],['id','<>',$row['id']]])->find()) {
                $this->error('系统中已经存在相同微信号');
            }

            if (!empty($post['qq']) && $this->model->where([['qq','=',trim($post['qq'])],['id','<>',$row['id']]])->find()) {
                $this->error('系统中已经存在相同QQ');
            }


            try {
                //已是有效客资，不进行修改此字段
                if (!empty($row['yx_status']) && !empty($post['yx_status'])) {
                    unset($post['yx_status']);
                }
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $where_str = '`edit`=1 AND `table`="crm_customer" AND `editinput` is not null';
        if (empty($row['yx_status'])) {
            $where_str = '('.$where_str.') or `field` = "yx_status" ';
        }
        $fields=Db::query('SELECT `editinput` FROM `system_field` WHERE '.$where_str.' order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=trim($v['editinput']);
        }
        $this->app->view->engine()->layout(false);
        if ($this->admin['isphone'] == 0) {
            $row['phone'] = mb_substr($row['phone'], 0, 3).'****'. mb_substr($row['phone'], 7, 11);
        }
        $fields_str=$this->display($fields_str,['row'=>$row]);
        $this->app->view->engine()->layout($this->layout);
        $this->assign('fields_str', $fields_str);
        return $this->fetch();
    }


    /**
     * 累计
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function lj_day_cache_num()
    {
        $num = Cache::store('redis')->get($this->day_cache_num_key);
        if (empty($num)) {
            $num = 0;
        }
        $num ++ ;
        //保存24小时
        Cache::store('redis')->set($this->day_cache_num_key,$num,24*60*60);
        return $num;
    }


/**
     * 随机分配参数
     * @return \int[][]
     */
    protected function get_distribution_arr()
    {
        return [
            [
                'v' => 10, 'id' => 3, 'username' => 'hongjian',
            ],
            [
                'v' => 9, 'id' => 22, 'username' => 'shaoyuxiang',
            ],
            [
                'v' => 6, 'id' => 23, 'username' => 'xupeiwen',
            ],
        ];
    }

    /**
     * 计算分配概率
     * @param $proArr
     * @return int|string
     */
    protected function getRand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);  //返回随机整数
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }


    /**
     * @NodeAnotation(title="添加")
     */
    public function seasadd()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post=$this->param_to_str($post);
            $this->verifyFields($post);
            //验证客户联系方式
            if (empty($post['phone']) && empty($post['wechat']) && empty($post['qq'])) {
                $this->error('客户联系电话、微信号、QQ必须填写一种');
            }

            if (!empty($post['phone']) && $this->model->where('phone', trim($post['phone']))->find()) {
                $this->error('系统中已经存在相同手机号');
            }

            if (!empty($post['wechat']) && $this->model->where('wechat', trim($post['wechat']))->find()) {
                $this->error('系统中已经存在相同微信号');
            }

            if (!empty($post['qq']) && $this->model->where('qq', trim($post['qq']))->find()) {
                $this->error('系统中已经存在相同QQ');
            }

             /*
            //查询销售经理，按比例进行划分
            $distribution_arr = $this->get_distribution_arr();
            foreach ($distribution_arr as $key => $val) {
                $arr[$key] = $val['v'];//概率数组
            }
            $rid = $this->getRand($arr); //根据概率获取分配id
            $admin_info = $distribution_arr[$rid];
            */
            //查询销售经理，按顺序分配一下
            /*
            $admin_list = [
                ['admin_id' => 16,'username' => 'mayingying'],
                ['admin_id' => 8,'username' => 'hewenhao'],
                ['admin_id' => 23,'username' => 'xupeiwen'],
                ['admin_id' => 22,'username' => 'shaoyuxiang'],
                ['admin_id' => 3,'username' => 'hongjian'],
            ];
            //查询当前销售今天的分配资源数据，逐个自动分配
            $max_count = 0;
            $date_time = strtotime(date('Y-m-d'));
            $admin_info = array();
            foreach ($admin_list as $ak => $admin) {
                $tmp_count =  $this->model->where('pr_user','=',$admin['username'])->where('create_time','>=',$date_time)->count('id');

                if (empty($tmp_count)) {
                    //视为命中销售
                    $admin_info = $admin;
                    break;
                }
                if ($tmp_count >= $max_count) {
                    //判断是否为最后一个
                    if ($ak == (count($admin_list) - 1 )) {
                        //取第一个进行分配
                        $admin_info = $admin_list[0];
                        break;
                    } else {
                        $max_count = $tmp_count;
                        continue;
                    }
                } else {
                    //视为命中销售
                    $admin_info = $admin;
                    break;
                }
            }
            //$admin_id = $admin_info['admin_id'];
            */

            $admin_id = $this->admin['admin_id'];

            //$pr_user_name = $admin_info['username'];

            # 引入adminModel
            $admin_model = new Admin();
            # 获取轮询结果
            $poll_data = $admin_model->getPollCustomerAdminId();
            if(!$poll_data['status']){
                $this->error($poll_data['msg']);
            }
            $post['pr_user'] = $poll_data['data']['username'];

            try {
                //状态为公海
                $post['status'] = 1;

                //20221204 此处按照比例，针对针对应人强抢归属
                //$post['status'] = 1;
                //$post['to_kh_time'] = time();
                //$post['pr_user'] = $pr_user_name;

                $post['at_user'] = $this->admin['username'];
                $save = $this->model->save($post);

            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
             $id = $this->model->id;

            // Db::table('crm_grab')->insert(['admin_id' => $admin_id, 'customer_id' => $id, 'createtime' => time()]);

            // //新增的客户会到公海，并进行企业微信提醒，由商务部进行认领
            // if (empty($post['source'])) {
            //     $post['source'] = '未知';
            // }
            // if (empty($post['source'])) {
            //     $post['source'] = '未知';
            // }
            // $num = $this->lj_day_cache_num();

            // $content = "编号：".date('d').str_pad($num,3,'0',STR_PAD_LEFT)."-".$id."\n名称：".$post['name']."\n需求：".$post['remark']."\n来源：".$post['source'];
            // $this->send_wx($content);

            $save ? $this->success('成功') : $this->error('失败');
        }
        $fields=Db::query('SELECT `addinput` FROM `system_field` WHERE `edit`=1 AND `table`="crm_customer" AND `addinput` is not null order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=trim($v['addinput']);
        }
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display($fields_str,['row'=>[]]);
        $this->app->view->engine()->layout($this->layout);
        $this->assign('fields_str', $fields_str);
        return $this->fetch();
    }


    //客户转移，变更负责人
    public function seas_alter_pr_user(){
        //1，获取提交的线索ID 【1,2,3,4,】
        $ids = $this->request->param('id');
        View::assign('ids',$ids);

        $user_list = Db::name('crm_customer')->where('id','in', $ids)->field('name')->select();
        $user_list = $user_list ? $user_list->toArray() : [];
        $user_names = [];
        foreach ($user_list as $v) {
            $user_names[] = $v['name'];
        }
        View::assign('user_names',implode(',', $user_names));

        //查询所有管理员
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username,realname')->select();
        View::assign('adminResult',$adminResult);

        if ($this->request->isAjax()){
            $username = Request::param('username');
            $idsArr = explode(",",$ids);

            $count = 0;
            foreach ($idsArr as  $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                $data['pr_user'] = $username;
                //从公海状态变更到客户状态
                $data['status']  = 1;
                $insertAll = Db::name('crm_customer')->where(['id'=>$value])->update($data);
                if ($insertAll){
                    $count ++;
                }
            }
            if ($count > 0){
                $this->success('转移'.$count.'个客户成功！');
            }else{
                $this->error('转移失败！');
            }
        }

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="成交客户")
     */
    public function issuccess()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where[]=['issuccess','=',1];
            $where[] = ['pr_user', '=', $this->admin['username']];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                if ($this->admin['isphone'] == 0) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);

                }
                //替换
                $value['pr_user_bef'] = $adminList[$value['pr_user_bef']]['realname'] ?? '';
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $value['at_user'] = $adminList[$value['at_user']]['realname'] ?? '';
                $list[$key] = $value;
            }


            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $fields=Db::query('SELECT `jscol` FROM `system_field` WHERE (`show`=1 AND `table`="crm_customer" AND `jscol` is not null) OR `field`="to_gh_time" OR `field`="pr_user_bef" order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=$v['jscol'].',';
        }
//        {"field":"source","title":"客户来源","search":"select","width":100,"selectList":"{:build_select_list('crm_source','name','name')}"}
        $fields_str=str_replace(['":"{:',')}"'],['":{:',')}'],$fields_str);
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display(trim($fields_str,','));
        $this->app->view->engine()->layout($this->layout);
//            cols_fields="([{"type": "checkbox"},"+CONFIG.cols_fields+" {"width": 250, "title": "操作", "templet": ea.table.tool}])";
        $this->assignconfig('cols_fields',json_decode('['.$fields_str.']',true));
        $this->assignconfig('parameter',['scope'=>$this->request->get('scope',1,'intval')]);
        return $this->fetch();
    }


        /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post=$this->param_to_str($post);
            $this->verifyFields($post);
            //验证客户联系方式
            if (empty($post['phone']) && empty($post['wechat']) && empty($post['qq'])) {
                $this->error('客户联系电话、微信号、QQ必须填写一种');
            }


            if (!empty($post['phone']) && $this->model->where('phone', trim($post['phone']))->find()) {
                $this->error('系统中已经存在相同手机号');
            }

            if (!empty($post['wechat']) && $this->model->where('wechat', trim($post['wechat']))->find()) {
                $this->error('系统中已经存在相同微信号');
            }

            if (!empty($post['qq']) && $this->model->where('qq', trim($post['qq']))->find()) {
                $this->error('系统中已经存在相同QQ');
            }

            $post['relaed_files'] = $post['file'];
            unset($post['file']);

            $post['at_user']=$this->admin['username'];
            $standing = explode(',', $this->admin['standing']);

            # 引入adminModel
            $admin_model = new Admin();

            //判断是否商务角色
            if(in_array($this->bus_standing, $standing)) {
                $post['pr_user'] = $this->admin['username'];
            } else {
//                $post['pr_user'] = $this->model->distributionCustomer();
                # 获取轮询结果
                $poll_data = $admin_model->getPollCustomerAdminId();
                if(!$poll_data['status']){
                    $this->error($poll_data['msg']);
                }
                $post['pr_user'] = $poll_data['data']['username'];
            }


//            try {
//                $save = $this->model->save($post);
//            } catch (\Exception $e) {
//                $this->error('保存失败:'.$e->getMessage());
//            }
//            $this->lj_day_cache_num();
//            $save ? $this->success('保存成功') : $this->error('保存失败');
            // 新增客户
            Db::startTrans();
            try{

                # 新增客户
                $add = $this->model->insertGetId($post);
                if(!$add){
                    throw new Exception("新增客户失败,请稍后重试");
                }

                # 更新商务最后轮询时间
                $update = $admin_model
                    ->where('username','=',$post['pr_user'])
                    ->where('is_poll','=',1)
                    ->save([
                        'last_poll_time'=>time(),
                    ]);
                if(!$update){
                    throw new Exception("轮询商务失败,请稍后重试");
                }

                Db::commit();
            }catch (Throwable $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            $this->success('新增客户成功 !');

        }
//        $fields=Db::query('SELECT `addinput` FROM `system_field` WHERE (`edit`=1 AND `table`="crm_customer" AND `addinput` is not null) or `field` = "yx_status" order BY `sort` ASC,id DESC');
        $fields=Db::query('SELECT `addinput` FROM `system_field` WHERE (`edit`=1 AND `table`="crm_customer" AND `addinput` is not null) order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=trim($v['addinput']);
        }
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display($fields_str,['row'=>[]]);
        $this->app->view->engine()->layout($this->layout);
        $this->assign('fields_str', $fields_str);
        return $this->fetch();
    }

    /**
     * 推送到企业微信
     * @param $post_data
     * @return bool
     */
    protected function send_wx($content)
    {
        #key=企业微信机器人中的值
        $webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=49c05b41-24b4-42db-8019-ef88868ceb94";   #这里需要修改
        //$webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=62a2b77f-b98d-4c8e-a56e-936fbe65c119";   #这里需要修改
        # curl初始化
        $curl = curl_init();
        #需要推送的url
        curl_setopt($curl, CURLOPT_URL, $webhook);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //验证curl对等证书(一般只要此项)
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); //检查服务器SSL证书中是否存在一个公用名
        curl_setopt($curl, CURLOPT_SSLVERSION, 0);  //传递一个包含SSL版本的长参数。
        #content必须是utf8编码
        curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=utf-8'));
        #content 为需要推送的内容
        $post_data = [
            'msgtype' => 'text',
            'text' => [
                'content' => $content,
                'mentioned_list' => ['@all']
            ],
        ];
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        //$error = curl_error($curl);
        curl_close($curl);
        if (empty($data)) {
            return false;
        }
        $data_arr = json_decode($data,true);
        if (isset($data_arr['errmsg']) && ($data_arr['errmsg'] == 'ok')) {
            return true;
        }
        return false;
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post=$this->param_to_str($post);
            $this->verifyFields($post);

            # 作废无效客资功能
            unset($post['yx_status']);
            unset($post['wx_remark']);
            # 作废无效客资功能

//            //已是有效客资，不进行修改此字段,已有无效状态
//            if ($row['yx_status'] >= 0) {
//                unset($post['yx_status']);
//                unset($post['wx_remark']);
//            }else {
//                //为-1默认状态，
//                if (empty($post['yx_status'])) {
//                    //此处为无效处理,增加无效字段的录入
//                    if (empty($post['wx_remark'])) {
//                        $this->error('无效客资说明不得为空');
//                    }
//
//                    //回到公海，重置状态
//
//                    $post['pr_user_bef'] = $row['pr_user'];
//                    if(empty($post['pr_user_bef'])){
//                        $post['pr_user_bef']='';
//                    }
//                    $post['pr_user'] = '';
//
//                    $post['to_gh_time'] = time();
//                    $post['status'] = 2;
//                }
//            }

            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $where_str = '`edit`=1 AND `table`="crm_customer" AND `editinput` is not null';
//        if ($row['yx_status'] < 0) {
//            $where_str = '('.$where_str.') or `field` = "yx_status" or `field` = "wx_remark" ';
//        }
        $fields=Db::query('SELECT `editinput` FROM `system_field` WHERE '.$where_str.' order BY `sort` ASC,id DESC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=trim($v['editinput']);
        }

        //根据无效状态，查询申诉记录
        //无效状态
        $appeal_info =  CrmCustomerAppeal::where(['customer_id' => $row['id']])->order('id DESC')->find();
        if (!empty($appeal_info)) {
            //存在申诉
            $fields_str .= '<div class="layui-form-item" style="color: red"><label class="layui-form-label">推广部无效客资申诉说明</label><div class="layui-input-block"><textarea style="color: red" readonly="ture"  class="layui-textarea textarea" >'.$appeal_info['explain'].'</textarea></div></div>';
        }

        $this->app->view->engine()->layout(false);
        if ($this->admin['isphone'] == 0) {
            $row['phone'] = mb_substr($row['phone'], 0, 3).'****'. mb_substr($row['phone'], 7, 11);
        }
        $fields_str=$this->display($fields_str,['row'=>$row]);

        $this->app->view->engine()->layout($this->layout);
        $this->assign('fields_str', $fields_str);
        return $this->fetch();
    }


    protected function verifyFields($post){
        $fields=Db::query('SELECT `name`,`xsname`,`rule`,`msg`,`field` FROM `system_field` WHERE rule <> "" AND `edit`=1 AND `table`="crm_customer" AND `editinput` is not null order BY `sort` ASC,id DESC');
        $rule=[];
        foreach ($fields as $v){
            $msg=!empty(trim($v['xsname']))?'|'.$v['xsname']:'|'.$v['name'];
            $ruleKey=$v['field'].$msg;
            $rule[$ruleKey]=str_replace('unique','unique:crm_customer',str_replace(',','|',$v['rule']));
        }
        if($rule){
            $this->validater($post, $rule);
        }
    }

    //客户转移，变更负责人
    public function alter_pr_user(){
        //1，获取提交的线索ID 【1,2,3,4,】
        $ids = $this->request->param('id');
        View::assign('ids',$ids);


        //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);

        if ($this->request->isAjax()){
            $username = Request::param('username');
            $idsArr = explode(",",$ids);

            $count = 0;
            foreach ($idsArr as  $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                $data['pr_user'] = $username;
                $insertAll = Db::name('crm_customer')->where(['id'=>$value])->update($data);
                if ($insertAll){
                    $count ++;
                }
            }
            if ($count > 0){
                $this->success('转移'.$count.'个客户成功！');
            }else{
                $this->error('转移失败！');
            }
        }

        return $this->fetch();
    }

    /**
     *批量导入客户
     */
    public function import()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post();

            if (!$params['filepath']) {
                $this->error('上传文件参数缺失！');
            }
            $filePath = $this->app->getRootPath().'public'.$params['filepath'];

            if (!is_file($filePath)) {
                $this->error('上传文件未找到！');
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error('请选择EXCEL表格式导入');
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
            } elseif ($ext === 'xls') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
            } else {
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");

            }



            //加载文件
            $insert = 0;
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error('获取文件数据失败');
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

                $fields=Db::query('SELECT `name`,`xsname`,`rule`,`msg`,`field` FROM `system_field` WHERE (rule <> "" AND `edit`=1 AND `table`="crm_customer" AND `editinput` is not null)  order BY `sort` ASC,id DESC');
                $rule=[];
                foreach ($fields as $v){
                    $name=$v['xsname']?$v['xsname']:$v['name'];
                    $msg=!empty(trim($v['msg']))?'|'.$v['msg']:'';
                    $ruleKey=$v['field'].$msg;
                    $rule[$ruleKey]=str_replace('unique','unique:crm_customer',str_replace(',','|',$v['rule']));
                }

                $fields = [];
//                获取第一列
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
//                        *客户名称(name)  获取字段
                        preg_match('/\((\S+)\)/',$val,$match);
                        if(!empty($match[1])){
                            $fields[$currentColumn] = $match[1];
                        }
                    }
                }
//第二行开始有数据
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $row = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = is_null($val) ? '' : $val;
                        $row[$fields[$currentColumn]]=$val;
                    }
//                    0-线索，1-客户，2-公海，3-删除
                    if($params['pr_user']){
                        $row['pr_user']=$params['pr_user'];
                        $row['status']=1;
                        $row['to_kh_time']=time();
                    }else{
                        $row['pr_user']='';
                        $row['status']=2;
                        $row['to_gh_time']=time();
                    }
                    $row['at_user']=$this->admin['username'];

                    if ($row) {
                        try {
                            if($rule){
                                parent::validate($row, $rule);
                            }
                            $result = Db::name('crm_customer')->save($row);
                            if ($result) {
                                $insert++;
                            }
                        } catch (\Exception $e) {
                            if ($params['skip'] != 1) {
                                throw new  exception($e->getMessage());
                            }
                        }

                    }
                }
            } catch (\Exception $exception) {

                $this->error('错误提示：'.$exception->getMessage() . "，当前行数：" . $currentRow);
            } catch (ValidateException $e) {

                $this->error('错误提示：'.$e->getMessage() . "当前行数：" . $currentRow);
            }
            if (!$insert) {
                $this->error('未插入任何数据');
            }
            $this->success("成功导入{$insert}条");
        }


//        Tree::instance()->init($groupList);
//        if ($this->auth->isSuperAdmin()) {
//            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
//            foreach ($result as $k => $v) {
//                $groupdata[$v['id']] = $v['name'];
//            }
//        } else {
//            $result = [];
//            $groups = $this->auth->getGroups();
//            foreach ($groups as $m => $n) {
//                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
//                $temp = [];
//                foreach ($childlist as $k => $v) {
//                    $temp[$v['id']] = $v['name'];
//                }
//                $result[__($n['name'])] = $temp;
//            }
//            $groupdata = $result;
//        }
//        $groupdata[0] = '选择归属组';
//        $this->view->assign('groupdata', $groupdata);
        return $this->fetch();
    }

    /**
     * 获取导入模板
     * @throws PDOException
     * @throws \think\db\exception\BindParamException
     */
    public function getImportTpl()
    {
        $fields=Db::query('SELECT `field`,`name`,`xsname`,`width`,`rule` FROM `system_field` WHERE `export`=1 AND `table`="crm_customer" order BY `sort` ASC,id DESC');
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $i = 0;
        foreach ($fields as $k => $v) {
            $name=$v['xsname']?$v['xsname']:$v['name'];
            if ($i >= 26) {
                $cell = chr(65 + $i / 26 - 1) . chr(65 + $i % 26);
            } else {
                $cell = chr(65 + $i);
            }
            $spreadsheet->getActiveSheet()->getStyle($cell . '1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('cdf79e');
            $required='';
            if(strpos($v['rule'],'require')!==false)$required='*';
            $sheet->getColumnDimension($cell)->setWidth($v['width'],'px');
            $sheet->setCellValue($cell . '1', $required.$name."({$v['field']})");
            $i++;
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename=customertpl.xlsx");
        header('Cache-Control: max-age=0');
        header('Cache-Control: cache, must-revalidate');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        try {
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        exit();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        @ini_set("memory_limit",'-1');
        @ini_set('max_execution_time', '0');

        list($page, $limit, $where) = $this->buildTableParamesScop();
//        只导出客户数据非公海数据
        $where[]=['status','=',1];
        $fields=Db::query('SELECT `field`,`name`,`xsname`,`width`,`rule`,`formtype`,`option` FROM `system_field` WHERE (`export`=1 OR `show`=1) AND `table`="crm_customer" order BY `sort` ASC,id DESC');
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $i = 0;
        $str_fields='`id`';
        $arr_fields=[];
        //var_dump($fields);exit;
        foreach ($fields as $k => $v) {
            $name=$v['xsname']?$v['xsname']:$v['name'];
            if ($i >= 26) {
                $cell = chr(65 + $i / 26 - 1) . chr(65 + $i % 26);
            } else {
                $cell = chr(65 + $i);
            }
            $worksheet->getStyle($cell . '1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('cdf79e');
            $worksheet->getColumnDimension($cell)->setWidth($v['width'],'px');
            if($v['field']!='id'){
                $str_fields=$str_fields.',`'.$v['field'].'`';
            }

            $arr_fields[$cell]=$v;
            $worksheet->setCellValue($cell . '1', $name);
            $i++;
        }
        $str_fields=trim($str_fields,',');
        $line=1;

        //查询所有管理员
        $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
        $adminList = [];
        foreach ($adminResult as $admin) {
            $adminList[$admin['username']] = $admin;
        }


        $this->model->field($str_fields)
            ->where($where)
            ->order($this->sort)
            ->chunk(100, function ($items) use ( &$line, &$worksheet,$arr_fields,$adminList) {
                $styleArray = array(
                    'font' => array(
                        'bold'  => false,
                        'color' => array('rgb' => '000000'),
                        'size'  => 12,
                        'name'  => 'Microsoft Yahei'
                    ));
                $items = $items->toArray();
                foreach ($items as $index => $item) {
                    $line++;
                    //替换
                    $item['pr_user_bef'] = $adminList[$item['pr_user_bef']]['realname'] ?? '';
                    $item['pr_user'] = $adminList[$item['pr_user']]['realname'] ?? '';
                    $item['at_user'] = $adminList[$item['at_user']]['realname'] ?? '';

                    foreach ($arr_fields as $cell => $field) {
                        $value=$item[$field['field']];

                        if($field['formtype']==='datetime'){
                            if(is_numeric($value) && $value>0){
                                $value=date('Y-m-d H:i:s',$value);
                            }elseif(is_numeric($value) && $value<1){
                                $value='';
                            }
                        }
                        if(($field['formtype']==='select' || $field['formtype']==='radio') && is_numeric($value) && !empty(trim($field['option']))){
                            $option=explode(',',$field['option']);
                            $selectList=[];
                            foreach ($option as $v){
                                $vv=explode(':',$v);
                                if($vv){
                                    $selectList[trim($vv[0])]=trim($vv[1]);
                                }
                            }
                            if(isset($selectList[$value])){
                                $value= $selectList[$value];
                            }
                        }
                        $worksheet->setCellValue($cell . $line, $value);
                        $worksheet->getStyle($cell . $line)->getNumberFormat()->setFormatCode('@');
                        $worksheet->getCell($cell . $line)->getStyle()->applyFromArray($styleArray);
                    }
                }
            });
        ob_end_clean();
        $title = date("YmdHis");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: cache, must-revalidate');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        try {
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }

        exit();
    }





}
